
import request from "@/base/request"
import Role from "@/types/role"
import { ElMessage } from "element-plus"
import {ref} from 'vue'
import Power from "@/types/power"

export default function(){

    interface RolePower{
        rolePermissionList:Array<Power>,
        remainPermissionList:Array<Power>
    }

    const rolePower=ref<RolePower>()

    const roleList=ref<Array<Role>>()

    const showSavePermission=ref(false)

    const saveUserPermissionParam=ref({
        roleId:0,
        roleName:"0",
        permissionIDList:[]
    })

    async function getRoleList() {
        const response = (await request.get("/user/admin/getRoleList")).data
        if(response.code===200){
            roleList.value=response.data
        }else{
            ElMessage.error(`获取失败，${response.msg}`)
        }
    }

    async function delRole(roleId:number) {
        const response=(await request.delete(`/user/admin/delRole/${roleId}`)).data
        if(response.code===200){
            ElMessage.success("删除成功");
            getRoleList();
        }else{
            ElMessage.error(`删除失败:${response.msg}`)
        }
    }

    async function getRolePower(roleId:number,roleName:string) {
        saveUserPermissionParam.value.roleId=roleId
        saveUserPermissionParam.value.roleName=roleName

        const response=(await request.get(`/user/admin/getRolePermission/${roleId}`)).data
        if(response.code===200){
            rolePower.value=response.data
        }else{
            ElMessage.error(`获取失败,${response.msg}`)
        }
    }


    async function saveUserPermission() {

        saveUserPermissionParam.value.permissionIDList=rolePower.value.rolePermissionList.map(rp=>{return rp.id})
        const response=(await request.post("/user/admin/saveUserPermission",saveUserPermissionParam.value)).data
        if(response.code===200){
            ElMessage.success('保存成功')
            showSavePermission.value=false
        }else{
            ElMessage.error(`保存失败,${response.msg}`)
        }
    }

    return {roleList,rolePower,showSavePermission,saveUserPermission,getRolePower,delRole,getRoleList}
}